import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '../store'

// 1.安装插件
Vue.use(VueRouter)

const routes = [{
		path: '/',
		name: 'Home',
		component: () => import('../views/Home.vue'),
		meta: {
			"title": "云端画廊"
		}
	},
	{
		path: '/error',
		name: 'Error',
		component: () => import('../components/Error.vue')
	},
	{
		path: '/payFinish',
		name: 'PayFinish',
		component: () => import('../views/PayFinish.vue'),
		meta: {
			requireAuth: true // 需要验证登录状态
		}
	},
	{
		path: '/goods',
		name: 'Goods',
		component: () => import('../views/Goods.vue')
	},
	{
		path: '/goods/details',
		name: 'Details',
		component: () => import('../views/Details.vue')
	},
	{
		path: '/Cart',
		name: 'Cart',
		component: () => import('../views/Cart.vue'),
		meta: {
			requireAuth: true // 需要验证登录状态
		}
	},
	{
		path: '/collect',
		name: 'Collect',
		component: () => import('../views/Collect.vue'),
		meta: {
			requireAuth: true // 需要验证登录状态
		}
	},
	{
		path: '/order',
		name: 'Order',
		component: () => import('../views/Order.vue'),
		meta: {
			requireAuth: true // 需要验证登录状态
		}
	},
	{
		path: '/confirmOrder',
		name: 'ConfirmOrder',
		component: () => import('../views/ConfirmOrder.vue'),
		meta: {
			requireAuth: true // 需要验证登录状态
		}
	},
	{

		path: '/profile',
		name: 'profile',
		component: () => import('../views/Profile.vue'),
		meta: {
			requireAuth: true // 需要验证登录状态
		}
	}
]

// 2.创建router对象
const router = new VueRouter({
	routes, // 传routes配置
	mode: 'history'
})

router.beforeEach((to, from, next) => {
	if (to.meta.title) {
		document.title = to.meta.title
	}
	next()
})

// 全局解析守卫：在进入需要用户权限的页面前校验是否已经登录
router.beforeResolve((to, from, next) => {
	const loginUser = store.state.user.user
	if (to.meta.requireAuth) { // 路由需要用户权限
		if (!loginUser) { // 没有登录
			store.dispatch("setShowLogin", true); // 显示登录组件
			if (from.name == null) { // /此时，是在页面没有加载，想直接通过地址栏进入需要登录验证的页面
				next("/");
				return;
			}
			// 终止导航
			next(false);
			return;
		}
	}
	next(); // 通过，跳转
})


// 3.导出router对象
export default router
